import { HttpException, Injectable } from '@nestjs/common';
import axios from 'axios';
import { parseQueryParams } from 'src/common/utils';
import { CreateProductDto } from 'src/dto/create-product.dto';
import { QueryProductDto } from 'src/dto/query-product.dto';
import { UpdateProductDto } from 'src/dto/update-product.dto';
import { Category } from 'src/entity/category.entity';
import { Product } from 'src/entity/product.entity';

@Injectable()
export class ProductService {
  async create(createProductDto: CreateProductDto) {
    let category = await Category.findOneBy({
      id: createProductDto.categoryId,
    });

    delete createProductDto.categoryId;

    let product = await Product.save({
      ...createProductDto,
      category,
    });

    return product;
  }

  async query(query: QueryProductDto) {
    console.log(
      '%c [ query ]-27',
      'font-size:13px; background:pink; color:#bf2c9f;',
      query,
    );
    let qeryBuilder = Product.createQueryBuilder('product');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, [
      'categoryId',
    ]);

    qeryBuilder.where(queryClone);

    if (query.categoryId) {
      qeryBuilder.andWhere('category.id = :categoryId', {
        categoryId: query.categoryId,
      });
    }

    // 关联分类
    qeryBuilder.leftJoinAndSelect('product.category', 'category');

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);

    let [list, count] = await qeryBuilder.getManyAndCount();

    return { list, count };
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Product.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      relations: ['category'],
    });

    return { list, count };
  }

  findOne(id: number) {
    return Product.findOne({ where: { id }, relations: ['category'] });
  }

  async update(id: number, updateProductDto: UpdateProductDto) {
    let category = await Category.findOneBy({
      id: updateProductDto.categoryId,
    });

    delete updateProductDto.categoryId;

    return Product.update(id, { ...updateProductDto, category });
  }

  remove(id: number) {
    return Product.update(id, { deleteTime: new Date() });
  }

  async gather(offerId: string) {
    // 从服务器获取1688产品详情

    let res: any = await axios.post(
      'https://api.callesetas.com/ali/queryProductDetail',
      {
        offerId,
        country: 'en',
      },
    );

    let product = res.data.data;

    // 保存数据到数据库
    let newProduct = {
      offerId: product.offerId,
      name: product.subjectTrans,
      mainImage: product.productImage.images[0],
      images: product.productImage.images.join(','),
      description: product.description,
      sku: JSON.stringify(product.productSkuInfos),
      price: product.productSkuInfos[0].consignPrice,
      status: 0,
    };

    console.log('newProduct', newProduct);

    if (product) {
      return await Product.save({ ...newProduct });
    } else {
      throw new HttpException('商品不存在', 400);
    }
  }
}
